const Koa = require('koa')
const Router = require('koa-router');
const mongoose = require('./db/mongo.js');
const app = new Koa()
const router = new Router();

const DB_URL = 'mongodb://master:master!123@localhost:27017/todos'
mongoose.connect(DB_URL)
const Cat = mongoose.model('Cat', { name: String });

// 对于任何请求，app将调用该异步函数处理请求：
app.use(async (ctx, next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    await next();
});

router.get('/hello', async (ctx, next) => {
    const data = await Cat.find({});
    console.log('data', data)
    ctx.response.body = JSON.parse(data)    
});

router.get('/hello/:name', async (ctx, next) => {
    let name = ctx.params.name;
    
    const kitty = new Cat({ name: name });
    kitty.save().then(() => console.log('meow'));
    ctx.response.body = `<h1>add, ${name}</h1>`
});

app.use(router.routes());


app.listen(3001);
console.log('app started at port http://localhost:3001/');


